var multiparty = require('multiparty');
var util = require('util');
var fs = require('fs');
var async = require('async');
var moment = require('moment');

var connPool = require('./connPool');
var Result = require('../jsBean/Result');

module.exports = {
	published: function (req, res, loginbean) {
		async.waterfall([
			function(done) {
				var form = new multiparty.Form();
				// 设置编码
				form.encoding = 'utf-8';
				// 设置文件存储路径，因为这个路由是根目录下的路由，所以直接写当前目录下的uploadtemp文件
				form.uploadDir = './uploadtemp/';
				// 设置单文件大小限制
				form.maxFilesSize = 2 * 1024 *1024;
			    form.parse(req, function (err, fields, files) {
			    	if(files["smallPicture"]) {
			    		
				    	// 通过index获取文件数据
						var file = files['smallPicture'];
						// 获取参数名
						var paraname = file[0].fieldName;
						// 获取原文件名
						var originalFilename = file[0].originalFilename;
						// 获取临时文件的存储路径
						var temPath = file[0].path;
						// 获取文件大小
						var fileSize = file[0].size;
						
						// 构造新存储路径
						var uploadurl = '/img/newsPicture/';
						// 拿到时间戳（字符串类型），拼接文件名，以免上传重名
						var timestamp = new Date().getTime();
						uploadurl += timestamp + originalFilename;
						// 得到新保存路径地址
						var newPath = './public' + uploadurl;
						
						// 准备读写操作
						// 准备读取临时文件路径
						var fileReadStream = fs.createReadStream(temPath);
						// 准备写入正式文件路径
						var fileWriteStream = fs.createWriteStream(newPath);
						// 准备就绪，开启管道流
						fileReadStream.pipe(fileWriteStream);
						// 监听写入事件，一旦写入完毕，执行回调函数
						fileWriteStream.on('close', function () {
							// 删除临时文件夹中的图片
							fs.unlinkSync(temPath);
							console.log('copy over');
							
							var data = {
								title: fields.title[0],
								smallTitle: fields.smallTitle[0],
								summary: fields.summary[0],
								content: fields.content[0],
								classify: fields.classify[0],
								smallPicture: uploadurl
							};
							done(null, data);
						});
			    	}else {
			    		var data = {
							title: fields.title[0],
							smallTitle: fields.smallTitle[0],
							summary: fields.summary[0],
							content: fields.content[0],
							classify: fields.classify[0],
							smallPicture: '/img/white.jpg'
						};
						done(null, data);
			    	}
			    });
				
				 
			},
			
			function(preValue, done) {
				var pool = connPool();
			
				pool.getConnection(function (err, conn) {
					if(err) {
						console.log(err.message);
						
						return;
					}
					 
					var newsInsertSql = 'INSERT news(title, smallTitle, summary, content, classify, sendCount, smallPicture) VALUES(?, ?, ?, ?, ?, ?, ?);';
					
					
					
					var param = [preValue.title, preValue.smallTitle, preValue.summary, preValue.content, preValue.classify, loginbean.account, preValue.smallPicture];
					
					conn.query(newsInsertSql, param, function (err, result) {
						if(err) {
							console.log(err.message);
							
							return;
						}
						
						conn.release();
						
						done(null, 1);
					});
				});
			}
		], function(err, rs) {
			if(err) {
				console.log(err);
				
				return;
			}
			
			var result = new Result();
			result.status = 1;
			
			res.send(result);
		
		});	 
	}, 
	
	publishedUpdate: function(req, res, loginbean) {
		async.waterfall([
			function(done) {
				var form = new multiparty.Form();
				// 设置编码
				form.encoding = 'utf-8';
				// 设置文件存储路径，因为这个路由是根目录下的路由，所以直接写当前目录下的uploadtemp文件
				form.uploadDir = './uploadtemp/';
				// 设置单文件大小限制
				form.maxFilesSize = 2 * 1024 *1024;
			    form.parse(req, function (err, fields, files) {
			    	console.log(files);
			    	if(files["smallPicture"]) {
				    	// 通过index获取文件数据
						var file = files['smallPicture'];
						// 获取参数名
						var paraname = file[0].fieldName;
						// 获取原文件名
						var originalFilename = file[0].originalFilename;
						// 获取临时文件的存储路径
						var temPath = file[0].path;
						// 获取文件大小
						var fileSize = file[0].size;
						
						// 构造新存储路径
						var uploadurl = '/img/newsPicture/';
						// 拿到时间戳（字符串类型），拼接文件名，以免上传重名
						var timestamp = new Date().getTime();
						uploadurl += timestamp + originalFilename;
						// 得到新保存路径地址
						var newPath = './public' + uploadurl;
						
						// 准备读写操作
						// 准备读取临时文件路径
						var fileReadStream = fs.createReadStream(temPath);
						// 准备写入正式文件路径
						var fileWriteStream = fs.createWriteStream(newPath);
						// 准备就绪，开启管道流
						fileReadStream.pipe(fileWriteStream);
						// 监听写入事件，一旦写入完毕，执行回调函数
						fileWriteStream.on('close', function () {
							// 删除临时文件夹中的图片
							fs.unlinkSync(temPath);
							console.log('copy over');
							
							var data = {
								title: fields.title[0],
								smallTitle: fields.smallTitle[0],
								summary: fields.summary[0],
								content: fields.content[0],
								classify: fields.classify[0],
								newsId: fields.newsId[0],
								smallPicture: uploadurl
							};
							done(null, data);
						});
			    	}else {
			    		var data = {
							title: fields.title[0],
							smallTitle: fields.smallTitle[0],
							summary: fields.summary[0],
							content: fields.content[0],
							classify: fields.classify[0],
							newsId: fields.newsId[0],
							smallPicture: fields.oldSmallPicture[0]
						};
						done(null, data);
			    	}
			    });
				
				 
			},
			
			function(preValue, done) {
				var pool = connPool();
			
				pool.getConnection(function (err, conn) {
					if(err) {
						console.log(err.message);
						
						return;
					}
					 
					var updateNewsSql = 'UPDATE news SET title=?, smallTitle=?, summary=?, content=?, classify=?, sendCount=?, smallPicture=? WHERE id=?;';
					var param = [preValue.title, preValue.smallTitle, preValue.summary, preValue.content, preValue.classify, loginbean.account, preValue.smallPicture, preValue.newsId];
					
					conn.query(updateNewsSql, param, function (err, result) {
						if(err) {
							console.log(err.message);
							
							return;
						}
						
						conn.release();
						
						done(null, 1);
					});
				});
			}
		], function(err, rs) {
			if(err) {
				console.log(err);
				
				return;
			}
			
			var result = new Result();
			result.status = 1;
			
			res.send(result);
		
		});	 
	},
	
	adminIndex: function (req, res, loginbean) {
		function timeTransform (time) {
			return moment(time).format('YYYY-MM-DD HH:mm:ss');
		}
		
		function cheeckPower(powerStr, power) {
			var arr = [];
			arr = powerStr.split(',');
			var flag = 0;
			for(var i=0; i<arr.length; i++) {
				if((arr[i] == power) || (arr[i] == "超级管理员")) {
					flag = 1;
				}
			}
			return flag;
		}
		
		var pool = connPool();
	
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}

			async.waterfall ([
				
				// 查询滚动新闻内容
				function(done) {
					if(cheeckPower(loginbean.power, '滚动')) {
						var selectNewsSql = 'SELECT id,title,smallTitle,sendCount,sendTime,click,comment FROM news WHERE classify=? ORDER BY id DESC;';
						var param = ['滚动'];
						
						conn.query(selectNewsSql, param, function (err, rs) {
							if(err) {
								console.log(err.message);
								
								return;
							}
							
							var rollNews = rs;
							rollNews.forEach(function (item) {
								item.sendTime = timeTransform(item.sendTime);
							});
							
							var data = {};
							data.rollNews = rollNews;
							
							done(null, data);
						});
					}else {
						var data = {};
						data.rollNews = ['no'];
							
						done(null, data);
					}
				},
				
				// 查询社会新闻内容
				function(data, done) {
					if(cheeckPower(loginbean.power, '社会')) {
						var selectNewsSql = 'SELECT id,title,smallTitle,sendCount,sendTime,click,comment FROM news WHERE classify=? ORDER BY id DESC;';
						var param = ['社会'];
						
						conn.query(selectNewsSql, param, function (err, rs) {
							if(err) {
								console.log(err.message);
								
								return;
							}
							
							var societyNews = rs;
							societyNews.forEach(function (item) {
								item.sendTime = timeTransform(item.sendTime);
							});
							
							data.societyNews = societyNews;
							
							done(null, data);
						});
					}else {
						data.societyNews = ['no'];
							
						done(null, data);
					}
				},
				
				// 查询娱乐新闻内容
				function(data, done) {
					if(cheeckPower(loginbean.power, '娱乐')) {
						var selectNewsSql = 'SELECT id,title,smallTitle,sendCount,sendTime,click,comment FROM news WHERE classify=? ORDER BY id DESC;';
						var param = ['娱乐'];
						
						conn.query(selectNewsSql, param, function (err, rs) {
							if(err) {
								console.log(err.message);
								
								return;
							}
							
							var amusementNews = rs;
							amusementNews.forEach(function (item) {
								item.sendTime = timeTransform(item.sendTime);
							});
							
							data.amusementNews = amusementNews;
							
							done(null, data);
						});
					}else {
						data.amusementNews = ['no'];
							
						done(null, data);
					}
				},
				
				// 查询科技新闻内容
				function(data, done) {
					if(cheeckPower(loginbean.power, '科技')) {
						var selectNewsSql = 'SELECT id,title,smallTitle,sendCount,sendTime,click,comment FROM news WHERE classify=? ORDER BY id DESC;';
						var param = ['科技'];
						
						conn.query(selectNewsSql, param, function (err, rs) {
							if(err) {
								console.log(err.message);
								
								return;
							}
							
							var scienceNews = rs;
							scienceNews.forEach(function (item) {
								item.sendTime = timeTransform(item.sendTime);
							});
							
							data.scienceNews = scienceNews;
							
							done(null, data);
						});
					}else {
						data.scienceNews = ['no'];
							
						done(null, data);
					}
				},
				
				// 查询体育新闻内容
				function(data, done) {
					if(cheeckPower(loginbean.power, '体育')) {
						var selectNewsSql = 'SELECT id,title,smallTitle,sendCount,sendTime,click,comment FROM news WHERE classify=? ORDER BY id DESC;';
						var param = ['体育'];
						
						conn.query(selectNewsSql, param, function (err, rs) {
							if(err) {
								console.log(err.message);
								
								return;
							}
							
							var PENews = rs;
							PENews.forEach(function (item) {
								item.sendTime = timeTransform(item.sendTime);
							});
							
							data.PENews = PENews;
							
							done(null, data);
						});
					}else {
						data.PENews = ['no'];
							
						done(null, data);
					}
				},
				
				// 查询财经新闻内容
				function(data, done) {
					if(cheeckPower(loginbean.power, '财经')) {
						var selectNewsSql = 'SELECT id,title,smallTitle,sendCount,sendTime,click,comment FROM news WHERE classify=? ORDER BY id DESC;';
						var param = ['财经'];
						
						conn.query(selectNewsSql, param, function (err, rs) {
							if(err) {
								console.log(err.message);
								
								return;
							}
							
							var financeNews = rs;
							financeNews.forEach(function (item) {
								item.sendTime = timeTransform(item.sendTime);
							});
							
							data.financeNews = financeNews;
							
							done(null, data);
						});
					}else {
						data.financeNews = ['no'];
							
						done(null, data);
					}
				},
				
				// 查询用户
				function(data, done) {
					var selectUserSql = 'SELECT id,name,account,email,createTime,state FROM user WHERE status=? ORDER BY id DESC;';
					var param = ['普通用户'];
					
					conn.query(selectUserSql, param, function (err, rs) {
						if(err) {
							console.log(err.message);
							
							return;
						}
						
						var user = rs;
						user.forEach(function (item) {
							item.createTime = timeTransform(item.createTime);
						});
						
						data.user = user;
						
						done(null, data);
					});
				},
				
				// 查询管理员
				function(data, done) {
					if(cheeckPower(loginbean.power, '超级管理员')) {
						var selectUserSql = 'SELECT id,name,account,email,createTime,state,power FROM user WHERE status=? OR status=? ORDER BY id DESC;';
						var param = ['管理员','超级管理员'];
						
						conn.query(selectUserSql, param, function (err, rs) {
							if(err) {
								console.log(err.message);
								
								return;
							}
							
							var adminUser = rs;
							adminUser.forEach(function (item) {
								item.createTime = timeTransform(item.createTime);
							});
							
							data.adminUser = adminUser;
							
							done(null, data);
						});
					}else {
						data.adminUser = ['no'];
							
						done(null, data);
					}
				}
				
			], function (err, data) {
				if(err) {
					console.log(err);
					conn.release();
					return;
				}
				
				conn.release();
				
				res.render('admin', {
					loginbean: loginbean,
					rollNews: data.rollNews,
					societyNews: data.societyNews,
					amusementNews: data.amusementNews,
					scienceNews: data.scienceNews,
					PENews: data.PENews,
					financeNews: data.financeNews,
					user: data.user,
					adminUser: data.adminUser
				});
			});
			 
		});
	},
	
	deleteNews: function (req, res, loginbean) {
		var pool = connPool();
			
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}
			 
			var deleteNewsSql = 'DELETE FROM news WHERE id=?;';
			var param = [req.body['newsId']];
			
			conn.query(deleteNewsSql, param, function (err, result) {
				if(err) {
					console.log(err.message);
					
					return;
				}
				
				conn.release();
				
				var result = new Result();
				result.status = 1;
				
				res.send(result);
			});
		});
	},
	
	deleteUser: function (req, res, loginbean) {
		var pool = connPool();
			
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}
			 
			var deleteUserSql = 'DELETE FROM user WHERE id=?;';
			var param = [req.body['userId']];
			
			conn.query(deleteUserSql, param, function (err, result) {
				if(err) {
					console.log(err.message);
					
					return;
				}
				
				conn.release();
				
				var result = new Result();
				result.status = 1;
				
				res.send(result);
			});
		});
	},
	
	deleteUserAdmin: function (req, res, loginbean) {
		var pool = connPool();
			
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}
			 
			var deleteUserSql = 'DELETE FROM user WHERE id=?;';
			var param = [req.body['userId']];
			
			conn.query(deleteUserSql, param, function (err, result) {
				if(err) {
					console.log(err.message);
					
					return;
				}
				
				conn.release();
				
				var result = new Result();
				result.status = 1;
				
				res.send(result);
			});
		});
	},
	
	createAdmin: function (req, res, loginbean) {
		function timeTransform (time) {
			return moment(time).format('YYYY-MM-DD HH:mm:ss');
		}
		var pool = connPool();
		
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}
			 
			async.waterfall ([
				
				function(done) {
					var userAddSql = 'INSERT user(name, account, password, email, status) VALUES(?, ?, ?, ?, "管理员");';
					var param = [req.body['name'], req.body['account'], req.body['password'], req.body['email']];
					
					conn.query(userAddSql, param, function (err, rs) {
						if(err) {
							console.log(err.message);
							var errorMessage = err.message;
							
							return;
						}
						
						done(null, 1);
					});
				},
				
				function (preValues, done) {
					var selectUserSql = 'SELECT * FROM user WHERE account=?;';
					var param = [req.body['account']];
					
					conn.query(selectUserSql, param, function (err, rs) {
						if(err) {
							console.log(err.message);
							
							return;
						}
						
						var userInfo = rs[0];
						userInfo.createTime = timeTransform(userInfo.createTime);
						done(null, userInfo);
					});
				}
			], function(err, userInfo) {
				if(err) {
					console.log(err);
					
					return;
				}
				
				conn.release();
				
				var result = new Result();
				result.status = 1;
				result.data = userInfo;
				
				res.send(result);
			});
		});
	},
	
	addPower: function (req, res, loginbean) {
		var powerValues = req.query['power'];
		
		var pool = connPool();
		
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}
			 
			async.waterfall ([
				
				function(done) {
					var updatePowerSql = 'UPDATE user SET power=power+? WHERE id=?;';
					var param = [req.body['power'], req.body['userId']];
					
					conn.query(updatePowerSql, param, function (err, rs) {
						if(err) {
							console.log(err.message);
							
							return;
						}
						
						done(null, 1);
					});
				},
				
				function (preValues, done) {
					var selectUserSql = 'SELECT power FROM user WHERE id=?;';
					var param = [req.body['userId']];
					
					conn.query(selectUserSql, param, function (err, rs) {
						if(err) {
							console.log(err.message);
							
							return;
						}
						
						var data = rs[0];
						
						done(null, data);
					});
				}
			], function(err, data) {
				if(err) {
					console.log(err);
					conn.release();
					return;
				}
				
				conn.release();
				
				var result = new Result();
				result.status = 1;
				result.data = data;
				
				res.send(result);
			});
		});
	},
	
	cutPower: function (req, res, loginbean) {
		var powerValues = req.query['power'];
		
		var pool = connPool();
		
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}
			 
			async.waterfall ([
				
				function(done) {
					var updatePowerSql = 'UPDATE user SET power=power-? WHERE id=?;';
					var param = [req.body['power'], req.body['userId']];
					
					conn.query(updatePowerSql, param, function (err, rs) {
						if(err) {
							console.log(err.message);
							var errorMessage = err.message;
							
							return;
						}
						
						done(null, 1);
					});
				},
				
				function (preValues, done) {
					var selectUserSql = 'SELECT power FROM user WHERE id=?;';
					var param = [req.body['userId']];
					
					conn.query(selectUserSql, param, function (err, rs) {
						if(err) {
							console.log(err.message);
							
							return;
						}
						
						var data = rs[0];
						
						done(null, data);
					});
				}
			], function(err, data) {
				if(err) {
					console.log(err);
					conn.release();
					return;
				}
				
				conn.release();
				
				var result = new Result();
				result.status = 1;
				result.data = data;
				
				res.send(result);
			});
		});
	},
	
	deleteComment: function (req, res, loginbean) {
		var commentId = parseInt(req.body['commentId']);
		var mainCommentObjectId = parseInt(req.body['mainCommentObjectId']);
		var newsId = req.body['newsId'];
		console.log(mainCommentObjectId);
		var pool = connPool();
		
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}
			
			if(!mainCommentObjectId) {
				var deleteCommentSql = 'DELETE FROM comment WHERE id=? OR mainCommentObjectId=?;';
				var param = [commentId, commentId];
				
				conn.query(deleteCommentSql, param, function (err, rs) {
					if(err) {
						console.log(err.message);
						
						return;
					}
					
					var selectCommentSql = 'SELECT COUNT(*) AS sum FROM comment WHERE newsId=?;';
					var param = [newsId];
					
					conn.query(selectCommentSql, param, function (err, rs) {
						if(err) {
							console.log(err.message);
							
							return;
						}
						
						var newComment = rs[0].sum;
						
						var updateNewsSql = 'UPDATE news SET comment=? WHERE id=?;';
						var param = [newComment, newsId];
						
						conn.query(updateNewsSql, param, function (err, rs) {
							if(err) {
								console.log(err.message);
								
								return;
							}
							
							conn.release();
							
							var result = new Result();
							result.status = 1;
							
							res.send(result);
						});
					});
				});
			}else {
				var deleteCommentSql = 'DELETE FROM comment WHERE id=?;';
				var param = [commentId];
				
				conn.query(deleteCommentSql, param, function (err, rs) {
					if(err) {
						console.log(err.message);
						
						return;
					}
					
					var updateNewsSql = 'UPDATE news SET comment=comment-1 WHERE id=?;';
					var param = [newsId];
					
					conn.query(updateNewsSql, param, function (err, rs) {
						if(err) {
							console.log(err.message);
							
							return;
						}
						
						conn.release();
						
						var result = new Result();
						result.status = 1;
						
						res.send(result);
					});
				});
			}
		});
	},
	
	newsUpdate: function (req, res, loginbean, newsId, classify) {
		var pool = connPool();
		
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}
			
			
			var selectNewsSql = 'SELECT * FROM news WHERE id=?;';
			var param = [newsId];
			
			conn.query(selectNewsSql, param, function (err, rs) {
				if(err) {
					console.log(err.message);
					
					return;
				}
				
				conn.release();
				
				res.render('newsPublish', { loginbean: loginbean, classify: classify, news: rs[0], newsId: newsId });
			});
		});
	},
	
	changeState: function (req, res, loginbean) {
		var pool = connPool();
		
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}
			
			var state = req.body['state'];
			var updateUserSql = 'UPDATE user SET state=? WHERE id=?;';
			var param = [state, req.body['userId'],];
			
			conn.query(updateUserSql, param, function (err, rs) {
				if(err) {
					console.log(err.message);
					
					return;
				}
				
				conn.release();
				
				var result = new Result();
				result.status = 1;
				result.data = {
					state: state
				};
				console.log(result);
				res.send(result);
			});
		});
	}
};
